package library.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import library.logger.Logger;

public class MD5Util {

    public static String getMD5FromFile(File file) {
        return getMD5FromFile(file, null);
    }

    public static String getMD5FromFile(File file, OnDigestProgressListener listener) {
        MessageDigest messagedigest = null;
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
        }
        if (messagedigest == null)
            return "";
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            long length = file.length();
            byte buffer[] = new byte[1024];
            int len;
            long size = 0;
            while ((len = is.read(buffer, 0, buffer.length)) != -1) {
                messagedigest.update(buffer, 0, len);
                if (listener != null) {
                    size += len;
                    listener.onDigestProgress((int) (size * 100 / length));
                }
            }
            BigInteger bigInt = new BigInteger(1, messagedigest.digest());
            return bigInt.toString(16).toUpperCase();
        } catch (Exception e) {
            Logger.debug(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return "";
    }

    public static String getMD5FromString(String s) {
        if (s == null)
            return "";
        return getMD5FromBytes(s.getBytes());
    }

    private static String getMD5FromBytes(byte[] bytes) {
        MessageDigest messagedigest = null;
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
        }
        if (messagedigest == null)
            return "";
        messagedigest.update(bytes);
        BigInteger bigInt = new BigInteger(1, messagedigest.digest());
        return bigInt.toString(16).toUpperCase();
    }


    interface OnDigestProgressListener {
        public void onDigestProgress(final int percent);
    }

}